package com.dog.modules.file.service.impl;

import cn.hutool.core.lang.Assert;
import com.dog.framework.core.exception.FileException;
import com.dog.framework.core.exception.ServiceException;
import com.dog.modules.file.model.SysFileUploadVO;
import com.dog.modules.file.service.OssService;
import com.dog.modules.file.utils.FileUtils;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;

/**
 * @author haoxr
 * @since 2023/6/2
 */
@Component
@ConditionalOnProperty(value = "oss.type", havingValue = "qiniu")
@ConfigurationProperties(prefix = "oss.qiniu")
@RequiredArgsConstructor
@Data
public class QiniuOssService implements OssService {

    private String domain;

    /**
     * 访问凭据
     */
    private String accessKey;
    /**
     * 凭据密钥
     */
    private String secretKey;
    /**
     * 存储桶名称
     */
    private String bucketName;


    private UploadManager uploadManager;


    // 依赖注入完成之后执行初始化
    @PostConstruct
    public void init() {
        uploadManager = new UploadManager(new Configuration(Region.autoRegion()));
    }

    /**
     * 上传文件
     *
     * @param file 表单文件对象
     * @return
     */
    @SneakyThrows
    @Override
    public SysFileUploadVO uploadFile(MultipartFile file) {
        SysFileUploadVO sysFileUploadVO = new SysFileUploadVO();
        String path = FileUtils.getPath(file.getOriginalFilename());
        try {
            String token = Auth.create(accessKey, secretKey).uploadToken(bucketName);
            Response res = uploadManager.put(file.getBytes(), path, token);
            if (!res.isOK()) {
                throw new ServiceException(res.toString());
            }
        } catch (Exception e) {
            throw new FileException("上传文件失败：", e.getStackTrace());
        }

        String fileUrl = domain + "/" + path;
        sysFileUploadVO.setUrl(fileUrl);
        sysFileUploadVO.setName(file.getOriginalFilename());
        sysFileUploadVO.setSize(file.getSize());
        sysFileUploadVO.setPlatform("qiniu");
        return sysFileUploadVO;
    }

    /**
     * 删除文件
     *
     * @param fileUrl 文件路径
     *                 https://oss.youlai.tech/default/20221120/test.jpg
     * @return
     */
    @SneakyThrows
    @Override
    public boolean deleteFile(String fileUrl) {
        Assert.notBlank(fileUrl, "删除文件路径不能为空");


        return true;
    }
}


